package com.the_ring.chapter09.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.material.tabs.TabLayout;
import com.the_ring.chapter09.R;
import com.the_ring.chapter09.adapter.ClassifyPagerAdapter;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ClassifyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClassifyFragment extends Fragment {

    private Context context;

    public ClassifyFragment(Context context) {
        // Required empty public constructor
        this.context = context;
    }

    public static ClassifyFragment newInstance(Context context) {
        ClassifyFragment fragment = new ClassifyFragment(context);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_classify, container, false);

        TabLayout headTab = view.findViewById(R.id.tl_head);
        ViewPager2 classifyVp = view.findViewById(R.id.vp_classify);

        headTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int count = headTab.getTabCount();
                for (int i = 0; i < count; i++) {
                    if (headTab.getTabAt(i) == tab) {
                        classifyVp.setCurrentItem(i, true);
                        break;
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        ClassifyPagerAdapter pagerAdapter = new ClassifyPagerAdapter( this, context);
        classifyVp.setAdapter(pagerAdapter);
        classifyVp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                headTab.selectTab(headTab.getTabAt(position));
            }
        });
        classifyVp.setCurrentItem(0);

        return view;
    }
}